package com.ruoyi.fun.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fun.domain.EcCategory;
import com.ruoyi.fun.service.IEcCategoryService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 商品分类Controller
 * 
 * @author ruoyi
 * @date 2025-08-06
 */
@RestController
@RequestMapping("/fun/category")
public class EcCategoryController extends BaseController
{
    @Autowired
    private IEcCategoryService ecCategoryService;

    /**
     * 查询商品分类列表
     */
    @PreAuthorize("@ss.hasPermi('fun:category:list')")
    @GetMapping("/list")
    public TableDataInfo list(EcCategory ecCategory)
    {
        startPage();
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        ecCategory.setOrgId(orgId);
        List<EcCategory> list = ecCategoryService.selectEcCategoryList(ecCategory);
        return getDataTable(list);
    }

    /**
     * 导出商品分类列表
     */
    @PreAuthorize("@ss.hasPermi('fun:category:export')")
    @Log(title = "商品分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EcCategory ecCategory)
    {
        List<EcCategory> list = ecCategoryService.selectEcCategoryList(ecCategory);
        ExcelUtil<EcCategory> util = new ExcelUtil<EcCategory>(EcCategory.class);
        util.exportExcel(response, list, "商品分类数据");
    }

    /**
     * 获取商品分类详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:category:query')")
    @GetMapping(value = "/{categoryId}")
    public AjaxResult getInfo(@PathVariable("categoryId") Long categoryId)
    {
        Long orgId = getOrgId();
        // 103组织拥有不过滤的权限
        if (orgId != null && orgId == 103L) {
            orgId = null;
        }
        return success(ecCategoryService.selectEcCategoryByCategoryIdAndOrgId(categoryId, orgId));
    }

    /**
     * 新增商品分类
     */
    @PreAuthorize("@ss.hasPermi('fun:category:add')")
    @Log(title = "商品分类", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EcCategory ecCategory)
    {
        ecCategory.setOrgId(getOrgId());
        return toAjax(ecCategoryService.insertEcCategory(ecCategory));
    }

    /**
     * 修改商品分类
     */
    @PreAuthorize("@ss.hasPermi('fun:category:edit')")
    @Log(title = "商品分类", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EcCategory ecCategory)
    {
        return toAjax(ecCategoryService.updateEcCategory(ecCategory));
    }

    /**
     * 删除商品分类
     */
    @PreAuthorize("@ss.hasPermi('fun:category:remove')")
    @Log(title = "商品分类", businessType = BusinessType.DELETE)
	@DeleteMapping("/{categoryIds}")
    public AjaxResult remove(@PathVariable Long[] categoryIds)
    {
        return toAjax(ecCategoryService.deleteEcCategoryByCategoryIds(categoryIds));
    }
    
    /**
     * 查询树形商品分类列表（公开接口）
     */
    @GetMapping("/tree")
    public TableDataInfo tree(EcCategory ecCategory)
    {
        // 只返回正常状态的分类
        if (ecCategory.getStatus() == null) {
            ecCategory.setStatus("0");
        }
        // 设置org_id过滤
        ecCategory.setOrgId(getOrgId());
        
        List<EcCategory> list = ecCategoryService.selectEcCategoryList(ecCategory);
        
        // 构建树形结构
        List<CategoryTreeNode> treeList = buildCategoryTree(list);
        
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(200);
        dataInfo.setMsg("查询成功");
        dataInfo.setRows(treeList);
        dataInfo.setTotal(treeList.size());
        
        return dataInfo;
    }
    
    /**
     * 构建分类树形结构
     */
    private List<CategoryTreeNode> buildCategoryTree(List<EcCategory> categories) {
        List<CategoryTreeNode> treeList = new java.util.ArrayList<>();
        
        // 找出所有父级分类（parentId为0或null）
        for (EcCategory category : categories) {
            if (category.getParentId() == null || category.getParentId() == 0) {
                CategoryTreeNode treeNode = new CategoryTreeNode();
                treeNode.setCategoryId(category.getCategoryId());
                treeNode.setParentId(category.getParentId());
                treeNode.setCategoryName(category.getCategoryName());
                treeNode.setCategoryCode(category.getCategoryCode());
                treeNode.setCategoryIcon(category.getCategoryIcon());
                treeNode.setCategoryImage(category.getCategoryImage());
                treeNode.setSortOrder(category.getSortOrder());
                treeNode.setStatus(category.getStatus());
                
                // 查找子分类
                List<CategoryTreeNode> children = findChildren(category.getCategoryId(), categories);
                treeNode.setChildren(children);
                
                treeList.add(treeNode);
            }
        }
        
        return treeList;
    }
    
    /**
     * 递归查找子分类
     */
    private List<CategoryTreeNode> findChildren(Long parentId, List<EcCategory> categories) {
        List<CategoryTreeNode> children = new java.util.ArrayList<>();
        
        for (EcCategory category : categories) {
            if (category.getParentId() != null && category.getParentId().equals(parentId)) {
                CategoryTreeNode childNode = new CategoryTreeNode();
                childNode.setCategoryId(category.getCategoryId());
                childNode.setParentId(category.getParentId());
                childNode.setCategoryName(category.getCategoryName());
                childNode.setCategoryCode(category.getCategoryCode());
                childNode.setCategoryIcon(category.getCategoryIcon());
                childNode.setCategoryImage(category.getCategoryImage());
                childNode.setSortOrder(category.getSortOrder());
                childNode.setStatus(category.getStatus());
                
                // 递归查找子分类的子分类
                List<CategoryTreeNode> grandChildren = findChildren(category.getCategoryId(), categories);
                childNode.setChildren(grandChildren);
                
                children.add(childNode);
            }
        }
        
        return children;
    }
    
    /**
     * 分类树节点
     */
    public static class CategoryTreeNode {
        private Long categoryId;
        private Long parentId;
        private String categoryName;
        private String categoryCode;
        private String categoryIcon;
        private String categoryImage;
        private Integer sortOrder;
        private String status;
        private List<CategoryTreeNode> children;
        
        // Getters and Setters
        public Long getCategoryId() { return categoryId; }
        public void setCategoryId(Long categoryId) { this.categoryId = categoryId; }
        
        public Long getParentId() { return parentId; }
        public void setParentId(Long parentId) { this.parentId = parentId; }
        
        public String getCategoryName() { return categoryName; }
        public void setCategoryName(String categoryName) { this.categoryName = categoryName; }
        
        public String getCategoryCode() { return categoryCode; }
        public void setCategoryCode(String categoryCode) { this.categoryCode = categoryCode; }
        
        public String getCategoryIcon() { return categoryIcon; }
        public void setCategoryIcon(String categoryIcon) { this.categoryIcon = categoryIcon; }
        
        public String getCategoryImage() { return categoryImage; }
        public void setCategoryImage(String categoryImage) { this.categoryImage = categoryImage; }
        
        public Integer getSortOrder() { return sortOrder; }
        public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; }
        
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        
        public List<CategoryTreeNode> getChildren() { return children; }
        public void setChildren(List<CategoryTreeNode> children) { this.children = children; }
    }
    /**
     * 根据categoryId和组织ID获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('fun:eccategory:query')")
    @GetMapping(value = "/{categoryId}/org/{orgId}")
    public AjaxResult getInfoByOrgId(@PathVariable("categoryId") Long categoryId, @PathVariable("orgId") Long orgId)
    {
        return success(ecCategoryService.selectEcCategoryByCategoryIdAndOrgId(categoryId, orgId));
    }

    /**
     * 根据组织ID查询列表
     */
    @PreAuthorize("@ss.hasPermi('fun:eccategory:list')")
    @GetMapping("/org/{orgId}")
    public TableDataInfo listByOrgId(@PathVariable Long orgId)
    {
        startPage();
        EcCategory ecCategory = new EcCategory();
        List<EcCategory> list = ecCategoryService.selectEcCategoryListByOrgId(ecCategory, orgId);
        return getDataTable(list);
    }


}

